<?php
//$Id: app.php 218 2012-03-21 02:52:48Z tomqin@gmail.com $

/**
 * App ARESCMS框架入口文件
 *
 * @copyright       Copyright (C) 2010-2012 ARESCMS Inc.
 * @author          TomQin <tomqin@gmail.com>
 * @license         http://www.arescms.cn/license/
 * @package Core
 */

if (!defined(PHP_VERSION_ID) || PHP_VERSION_ID < 50400) die('PHP Version have to be more than 5.4!');

//ARESCMS应用程序框架
if (!defined('ARESCMS_PATH')) die('Define `ARESCMS_PATH` first!');

//框架标记
define('IN_ARESCMS', true);

//路径分割符
define('DS', DIRECTORY_SEPARATOR);

//ARESCMS库框架路径
define('AC_PATH', __DIR__.DS);

//缓存文件夹地址
define('DATA_PATH', ARESCMS_PATH.'data'.DS);

//主机协议
define('SITE_PROTOCOL', isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://');

//当前访问的主机名
define('SITE_URL', (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''));

//来源
define('HTTP_REFERER', isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '');

//系统开始时间
define('SYS_START_TIME', microtime(true));
define('TIMESTAMP', $_SERVER['REQUEST_TIME']);

//基础函数库
require_once AC_PATH.'function'.DS.'global.func.php';

//载入核心
if (file_exists(AC_PATH.'core.min.php')) {
    require_once AC_PATH.'core.min.php';
}else{
    require_once AC_PATH.'library'.DS.'db.php';
    require_once AC_PATH.'library'.DS.'view.php';
    require_once AC_PATH.'library'.DS.'config.php';
    require_once AC_PATH.'library'.DS.'cookie.php';
    require_once AC_PATH.'library'.DS.'cache.php';
}

//设置错误信息
error_reporting(E_ALL ^ E_NOTICE);
//set_error_handler('my_error_handler');


//设置本地时差
date_default_timezone_set(Config::get('system.timezone'));

//系统字符集
define('CHARSET', Config::get('system.charset'));

//系统路径
define('STATIC_URL',  Config::get('system.static_url'));
define('UPLOAD_URL',  Config::get('system.upload_url'));
define('UPLOAD_PATH', Config::get('system.upload_path'));

//IP地址
define('IP_ADDRESS', ip_address());

//输出页面字符集
header('Content-type: text/html; charset='.CHARSET);

//GZIP 输出模式
if (Config::get('system.gzip') && function_exists('ob_gzhandler')) {
    ob_start('ob_gzhandler');
} else {
    ob_start();
}


// $Id: app.php 218 2012-03-21 02:52:48Z tomqin@gmail.com $

/**
 * App 应用程序框架基本操作类
 *
 * @copyright       Copyright (C) 2010-2012 ARESCMS Inc.
 * @author          TomQin <tomqin@gmail.com>
 * @license         http://www.arescms.cn/license/
 * @package Core
 */

class App
{
    static $_config = array();

    public static function adminUrl($c, $a = '', $params = array()) {
        $url = '?c='.trim($c).'&a='.trim($a);
        if (!empty($params))
            $url .= '&'.http_build_query($params);
        return $url;
    }

    public static function frontUrl($c, $a = '', $other = '') {
        $url = '/'.trim($c).'/'.urlencode($a);
        if (!empty($other)) {
            if (is_array($other))
                $url .= '/?'.http_build_query($other);
            else
                $url .= '/'.$other;
        }

        return $url;
    }

    public static function getCityId() {
        $cityid = Cookie::get('cityid');
        if (!$cityid) {
            $cityid = Config::get('default.cityid');
        }
        return $cityid;
    }

    /**
     * 记录日志
     *
     * @param string    日志信息
     * @param string    日志级别
     * @return void
     */
    public static function log($message, $level = 'ERR') {
        $now = date('[ c ]');
        $logfile = LOG_PATH . date('y_m_d') . '.log';
        //检测日志文件大小，超过配置大小则备份日志文件重新生成
        if (is_file($logfile) && floor(self::getConfig('log.max_file_size')) <= filesize($logfile)) {
            rename($logfile, dirname($logfile) . '/' . time() . '-' . basename($logfile));
        }

        error_log("{$now} {$level}: {$message}\r\n", 3, $logfile);//写入错误日志
    }

    /**
     * 载入系统方法
     *
     * @param $string   文件名
     */
    public static function loadFunction($file) {
        $file = AC_PATH . 'function' . DS . strtolower($file) . '.func.php';
        if (file_exists($file)) {
            require_once $file;
        }
    }

    /**
     * 载入系统类库
     *
     * @param $string   文件名
     * @return string   类名
     * @throw Exception
     */
    public static function loadLibrary($file, $args = null) {
        return self::_load_class('library', $file, $args);
    }

    /**
     * 载入模型类
     *
     * @param $string   文件名
     * @return string   类名
     * @throw Exception
     */
    public static function loadModule($file, $args = null) {
        static::loadLibrary('Module');
        return self::_load_class('module', $file, $args);
    }

    /**
     * 通用载入类库
     *
     * @param string    类型
     * @param string    文件名，可以使用"/"区分目录
     * @return Object
     * @throw Exception
     */
    private static function _load_class($type, $file, $args) {
        static $classes = array();

        $class = basename($file);
        $class = ($type == 'library') ? $class : "{$class}_{$type}";

        if (!class_exists($class)) {
            $file = AC_PATH . strtolower($type . DS . $file) . '.php';
            if (file_exists($file)) {
                require_once $file;
            }else{
                new Exception('There is no '.$type.' class `' .$class. '`');
            }
        }

        if (method_exists($class, '__construct')){
            if (isset($classes[$class]) && is_a($classes[$class], $class)) {
                $object = $classes[$class];
            } else {
                $refClass = new ReflectionClass($class);
                $object = ($args === null) ? $refClass->newInstance() : $refClass->newInstanceArgs($args);
                $classes[$class] = $object;
            }
            return $object;
        }
    }

    /**
     * 载入 Mysql
     *
     * @return Mysql
     */
    public static function getDb() {
        return Db::instance(Config::get('database.default'));
    }

    /**
     * 载入 User
     *
     * @return User
     */
    static function getUser() {
        //App::loadLibrary('user');
        return new AdminUser();
    }

    static function getAdminUser() {
        //App::loadLibrary('user');
        return new AdminUser();
    }
}
?>